package com.zhengshang.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhengshang.api.domain.AppOtherQueryRecord;
import com.zhengshang.api.service.IAppOtherQueryRecordService;
import com.zhengshang.common.annotation.RepeatSubmit;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.common.utils.http.HttpUtils;
import com.zhengshang.security.service.TokenService;
import com.zhengshang.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HY
 * @version 1.0.0
 * @ClassName ViolationController.java
 * @Description TODO
 * @createTime 2021年04月08日 09:07
 */
@Api(tags = "违章查询接口")
@RestController
@RequestMapping("/violation")
public class ViolationController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IAppOtherQueryRecordService appOtherQueryRecordService;

    @ApiOperation(value = "根据车牌前缀获取城市参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "hphm", value = "车牌前缀(前2位)，如：豫A", dataType = "String", paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('app:violation:query')")
    @RepeatSubmit
    @PostMapping("/getCarPre")
    public AjaxResult getCarPre(
            @RequestParam String hphm,
            HttpServletRequest request, HttpServletResponse response){
        try {
            if (StringUtils.isBlank(hphm)) {
                return AjaxResult.error("参数异常");
            }
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("key", AppConstant.JHDATA_VIOLATION_KEY);
            paramMap.put("hphm", URLEncoder.encode(hphm, "UTF-8"));
            String result = HttpUtils.sendGet(AppConstant.JHDATA_VIOLATION_CARPRE_URL, HttpUtils.getParam(paramMap));
            return convertJuheData(result, false, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation(value = "违章查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "hphm", value = "号牌号码 完整7位", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "hpzl", value = "号牌类型，默认02:小型车，01:大型车", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "engineno", value = "发动机号 (具体是否需要根据城市接口中的参数填写)", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "classno", value = "车架号 (具体是否需要根据城市接口中的参数填写)", required = false, dataType = "String", paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('app:violation:query')")
    @RepeatSubmit
    @PostMapping("/query")
    public AjaxResult query(
            @RequestParam String hphm,
            @RequestParam String hpzl,
            @RequestParam(required = false) String engineno,
            @RequestParam(required = false) String classno,
            HttpServletRequest request, HttpServletResponse response){
        try {
            if (StringUtils.isBlank(hphm) || StringUtils.isBlank(hpzl)) {
                return AjaxResult.error("参数异常");
            }
            hphm = hphm.trim();
            if (hphm.length() != 7) {
                return AjaxResult.error("请输入正确的号牌号码");
            }
            if (!"01".equals(hpzl) && !"02".equals(hpzl)) {
                return AjaxResult.error("号牌种类不正确");
            }
            String countStr = configService.selectConfigByKey("app.violation.query.count");//每日查询次数
            int count = Integer.parseInt(countStr);
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            AppOtherQueryRecord appOtherQueryRecord = new AppOtherQueryRecord();
            appOtherQueryRecord.setUserId(loginAppUser.getAppUser().getUserId());
            appOtherQueryRecord.setCreateTime(DateUtils.getNowDate());
            appOtherQueryRecord.setQueryType("1");
            if (appOtherQueryRecordService.getTodayCount(appOtherQueryRecord) >= count) {
                return AjaxResult.error("今日查询次数已达上限，请明天再试吧");
            }
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("key", AppConstant.JHDATA_VIOLATION_KEY);
            paramMap.put("dtype", "json");
            paramMap.put("hphm", URLEncoder.encode(hphm, "UTF-8"));
            paramMap.put("hpzl", hpzl);
            if (StringUtils.isNotBlank(engineno)) paramMap.put("engineno", engineno.trim());
            if (StringUtils.isNotBlank(classno)) paramMap.put("classno", classno.trim());
            String result = HttpUtils.sendGet(AppConstant.JHDATA_VIOLATION_QUERY_URL, HttpUtils.getParam(paramMap));
            return convertJuheData(result, true, loginAppUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    /**
     * @title
     * @param resultStr  返回结果json字符串
     * @param saveRecord  是否保存记录
     * @author admin
     * @updateTime 2021/4/8 11:44
     * @throws
     */
    private AjaxResult convertJuheData(String resultStr, boolean saveRecord, LoginAppUser loginAppUser) {
        if (com.zhengshang.common.utils.StringUtils.isBlank(resultStr) || resultStr.indexOf("{") == -1 || resultStr.indexOf("}") == -1) {
            return AjaxResult.error(resultStr);
        }
        JSONObject object = JSONObject.parseObject(resultStr);
        logger.info("<violation." + Thread.currentThread().getStackTrace()[2].getMethodName() + ">" + resultStr);
        if (object.getIntValue("error_code") == 0) {
            if (saveRecord && loginAppUser != null) {
                //保存记录
                AppOtherQueryRecord appOtherQueryRecord = new AppOtherQueryRecord();
                appOtherQueryRecord.setUserId(loginAppUser.getAppUser().getUserId());
                appOtherQueryRecord.setResultData(resultStr);
                appOtherQueryRecord.setCreateBy(loginAppUser.getUsername());
                appOtherQueryRecord.setQueryType("1");
                appOtherQueryRecordService.insertAppOtherQueryRecord(appOtherQueryRecord);
            }
            if (object.get("result") instanceof JSONObject)
                return AjaxResult.success("查询成功", object.getJSONObject("result"));
            if (object.get("result") instanceof JSONArray)
                return AjaxResult.success("查询成功", object.getJSONArray("result"));
            return AjaxResult.success("查询成功", object.get("result"));
        }
        return AjaxResult.success(object.getString("reason"));
    }
}
